<template>
  <a-card>
    <div class="home">
      <div class="searchNav" style="display: flex; justify-content: space-between">
        <div>
          <a-button
            class="button"
            icon="plus"
            type="primary"
            style="margin-left: 0; margin-bottom: 10px"
            :loading="loading"
            @click="dialogConfirm"
          >新增</a-button
          >
          <a-button
            class="button"
            icon="redo"
            type="primary"
            style="margin-left: 20px; margin-bottom: 10px"
            :loading="redoLoading"
            @click="aync"
          >生成销货清单</a-button
          >
          <span style="margin-left: 20px; margin-bottom: 10px">排序方式(倒序)</span>
          <a-switch
            checked-children="发货日期"
            style="margin-bottom: 10px"
            un-checked-children="制单日期"
            v-model="qryDate"
            @change="(...args) => updateRunStatus(...args)"
          />
          <span style="margin-left: 20px; margin-bottom: 10px">状态：</span>
          <el-select v-model="queryParam.Status" style="margin-left: 5px; margin-bottom: 10px" placeholder="筛选状态">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <el-radio-group style="margin-left: 10px" v-model="queryParam.IsClose">
            <el-radio :label="1">已开启</el-radio>
            <el-radio :label="0">已关闭</el-radio>
          </el-radio-group>
          <div style="margin: 10px 0">
            <a-select
              style="width: 100px; margin-left: 8px"
              v-model="selectTime"
              @change="changeTime"
              name="radioGroup"
              :default-value="0"
            >
              <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                {{ i }}
              </a-select-option>
            </a-select>

            <a-range-picker
              style="margin-left: 8px; width: 220px"
              :disabled="timeDisabled"
              valueFormat="YYYY-MM-DD"
              v-model="time"
            />
          </div>
        </div>
        <div class="searchParams" style="display: flex; padding-bottom: 10px">
          <div>
            <radioGroup @radioChange="radioChange" @complete="radioComplete" />
          </div>

          <searchTip
            v-model="queryParam.keyword"
            style="margin: 0 10px"
            placeholder="请输入出库单号 / 购货单位"
            :list="searchTipResultList"
            @change="toGetSearchTipList"
            @enterKeyDown="getDataList"
            @blur="keywordBlurFun"
            @select="selectSearchTipFun"
          />

          <a-button
            class="button"
            @click="
              () => {
                this.pagination.current = 1
                this.getDataList()
              }
            "
            style="background-color: #1890ff; color: #fff"
          >查询</a-button
          >
        </div>
      </div>

      <div style="position: relative">
        <div>
          <el-table height="calc(100vh - 310px)" :scroll="{ y: 'calc(100vh - 460px)' }" :data="tableData" style="width: 100%" v-loading="loading">
            <!-- <el-table-column prop="CompanyName" label="所属公司" width="250">
      </el-table-column> -->
            <el-table-column prop="BillId" label="发票编号" width="180px"> </el-table-column>
            <!-- <el-table-column prop="InvoiceCode" label="发票编号" width="180px"> </el-table-column> -->
            <el-table-column prop="CreateTime" label="制单日期" width="120">
              <template slot-scope="scope">
                {{ scope.row.CreateTime ? scope.row.CreateTime.substring(0, 10) : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="MadeDate" label="发货日期" width="120">
              <template slot-scope="scope">
                {{ scope.row.MadeDate ? scope.row.MadeDate.substring(0, 10) : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="Customer" label="购货单位" width="300"> </el-table-column>
            <el-table-column prop="TotalQuantity" label="数量">
              <template slot-scope="scope">
                {{ scope.row.TotalQuantity ? scope.row.TotalQuantity.toFixed(4) : 0 }}
              </template></el-table-column
            >
            <el-table-column prop="TotalMoney" label="金额">
              <template slot-scope="scope">
                {{ scope.row.TotalMoney ? scope.row.TotalMoney.toFixed(2) : 0.0 }}
                <!-- {{ $options.filters.NumberFormatss(scope.row.TotalMoney || 0) }} -->
              </template>
            </el-table-column>
            <el-table-column prop="TotalMoney" label="开票金额">
              <template slot-scope="scope">
                {{ scope.row.InvoicingMoney ? scope.row.InvoicingMoney.toFixed(2) : 0.0 }}
                <!-- {{ $options.filters.NumberFormatss(scope.row.TotalMoney || 0) }} -->
              </template>
            </el-table-column>
            <!-- <el-table-column prop="ContactPersonName" label="收货人">
        <template slot-scope="scope">
          {{ scope.row.ContactPersonName }}
          {{
            scope.row.ContactPersonName && scope.row.CustomerPhone ? "/" : ""
          }}
          {{ scope.row.CustomerPhone }}
        </template>
      </el-table-column> -->
            <!-- <el-table-column prop="FullName" label="签收人">
          <template slot-scope="scope">
            {{ scope.row.FullName }}
            {{ scope.row.FullName && scope.row.ReceiptPhone ? '/' : '' }}
            {{ scope.row.ReceiptPhone }}
          </template>
        </el-table-column> -->
            <!-- <el-table-column prop="CustomerPhone" label="签收手机号" width="130">
            <template slot-scope="scope">
              {{
                scope.row.CustomerPhone != "暂无" ? scope.row.CustomerPhone : ""
              }}
            </template>
          </el-table-column> -->
            <el-table-column prop="Status" label="状态" width="100" align="center">
              <template slot-scope="scope">
                <el-tag class="tableEltag" v-if="scope.row.Status == 0">待签收</el-tag>
                <el-tag class="tableEltag" v-if="scope.row.Status == 1" type="success">已签收</el-tag>
                <el-tag class="tableEltag" v-if="scope.row.Status == 2" type="danger">已拒收</el-tag>
                <el-tag class="tableEltag" v-if="scope.row.Status == 3" type="warning">有差异</el-tag>
                <el-tag class="tableEltag" v-if="scope.row.Status == 4" type="danger">已作废</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="标记" width="100" align="center">
              <template slot-scope="scope">
                <el-tag class="tableEltag" v-for="item in scope.row.Tag ? scope.row.Tag.split(',') : []" :key="item">
                  {{ item }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="开启/关闭" width="100" align="center">
              <template slot-scope="scope">
                <el-tag class="tableEltag">
                  {{ scope.row.IsClose ? '已开启' : '已关闭' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-dropdown>
                  <span class="el-dropdown-link"> 操作<i class="el-icon-arrow-down el-icon--right"></i> </span>
                  <el-dropdown-menu slot="dropdown">
                    <div style="display: flex; flex-direction: column">
                      <el-popconfirm
                        v-if="scope.row.IsClose"
                        confirm-button-text="确认"
                        canca-button-text="取消"
                        canca-button-type=""
                        title="此操作将关闭当前回执单,确认继续吗?"
                        @confirm="changeType(scope.row, 0)"
                      ><el-link
                        style="margin: 0 0 5px 0; width: 100px"
                        slot="reference"
                        type="primary"
                        class="linkmargin"
                        :underline="false"
                      >关闭</el-link
                      >
                      </el-popconfirm>
                      <el-popconfirm
                        v-if="!scope.row.IsClose"
                        confirm-button-text="确认"
                        canca-button-text="取消"
                        canca-button-type=""
                        title="此操作将重启当前回执单,确认继续吗?"
                        @confirm="changeType(scope.row, 1)"
                      ><el-link
                        style="margin: 0 0 5px 0; width: 100px"
                        slot="reference"
                        type="primary"
                        class="linkmargin"
                        :underline="false"
                      >重启</el-link
                      >
                      </el-popconfirm>
                      <el-link
                        style="margin: 0 0 5px 0; width: 100px"
                        type="primary"
                        :underline="false"
                        v-if="hasPerm('waybill.import')"
                        @click="upInfo(scope.row)"
                      >
                        &nbsp;&nbsp;导入 &nbsp;&nbsp;
                      </el-link>

                      <el-link
                        style="margin: 0 0 5px 0; width: 100px"
                        type="primary"
                        :underline="false"
                        v-if="hasPerm('waybill.export')"
                        @click="download(scope.row)"
                      >
                        &nbsp;&nbsp;导出 &nbsp;&nbsp;
                      </el-link>

                      <el-link
                        style="margin: 0 0 5px 0; width: 100px"
                        type="primary"
                        :underline="false"
                        v-if="hasPerm('waybill.select')"
                        @click="handelOpen(scope.row)"
                      >
                        &nbsp;&nbsp;标记 &nbsp;&nbsp;
                      </el-link>
                      <el-link
                        class="linkmargin"
                        style="margin: 0 0 5px 0; width: 100px"
                        v-if="scope.row.Status == 0 && hasPerm('waybill.edit')"
                        type="primary"
                        :underline="false"
                        @click="openwaybillForm(scope.row)"
                      >
                        &nbsp;&nbsp;编辑 &nbsp;&nbsp;
                      </el-link>
                      <el-link
                        style="margin: 0 0 5px 0; width: 100px"
                        v-if="scope.row.Status != 4 && hasPerm('waybill.view')"
                        type="primary"
                        :underline="false"
                        class="linkmargin"
                        @click="openNewPage(scope.row)"
                      >
                        &nbsp;&nbsp;查看 &nbsp;&nbsp;
                      </el-link>
                      <el-popconfirm
                        v-if="scope.row.Status == 3"
                        confirm-button-text="确认"
                        canca-button-text="取消"
                        canca-button-type=""
                        title="此操作将同意当前回执单差异,确认继续吗?"
                        @confirm="differentConfrim(scope.row)"
                      ><el-link
                        style="margin: 0 0 5px 0; width: 100px"
                        slot="reference"
                        type="primary"
                        class="linkmargin"
                        :underline="false"
                      >确认</el-link
                      >
                      </el-popconfirm>
                      <!-- <el-link
              v-if="scope.row.Status < 3"
              type="primary"
              :underline="false"
              class="linkmargin"
              @click="handleDownload(scope.row)"
            >下载 &nbsp;&nbsp;
            </el-link> -->
                      <el-link
                        style="margin: 0 0 5px 0; width: 100px"
                        v-if="scope.row.Status == 0 && hasPerm('waybill.delete')"
                        type="danger"
                        class="linkmargin"
                        :underline="false"
                        @click="handleInvalidate(scope.row)"
                      >
                        &nbsp;&nbsp;作废 &nbsp;&nbsp;
                      </el-link>
                      <div v-if="hasPerm('waybill.split')">
                        <el-link
                          v-if="
                            scope.row.Status == 0 ||
                              scope.row.Status == 1 ||
                              scope.row.Status == 2 ||
                              scope.row.Status == 3
                          "
                          style="margin: 0 0 5px 0; width: 100px"
                          class="linkmargin"
                          type="primary"
                          :underline="false"
                          @click="openwaybillFormSplit(scope.row)"
                        >
                          &nbsp;&nbsp;拆单 &nbsp;&nbsp;
                        </el-link>
                      </div>
                    </div>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <div style="position:absolute;bottom:-30px;">
            <span>合计金额：{{ PriceTotal | NumberFormats }}</span>
            <span style="margin-left: 10px;">合计数量：{{ TotalQuantity.toFixed(2) }}</span>
          </div>
        </div>
      </div>
      <el-pagination
        layout="total,prev, pager, next,sizes"
        :total="pagination.total"
        :current-page="pagination.current"
        :page-size="pagination.pageSize"
        :page-sizes="pagination.pageSizeOptions"
        style="text-align: right; margin-top: 8px; padding: 0"
        @current-change="currentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
      <el-dialog title="选择模板" width="30%" :visible.sync="dialogVisible">
        <el-select v-model="templateId" placeholder="请选择模板" style="width: 100%">
          <el-option
            v-for="(item, index) in templateList"
            :key="item.Id"
            :label="item.TemName"
            :value="index"
          ></el-option>
        </el-select>
        <div slot="footer" class="dialog-footer">
          <a-button @click="dialogVisible = false">取 消</a-button>
          <a-button type="primary" @click="dialogConfirm">确 定</a-button>
        </div>
      </el-dialog>
      <el-dialog title="添加标记" width="30%" :visible.sync="inputDialogVisible" :close-on-click-modal="false">
        <el-tag
          :key="tag"
          v-for="tag in dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
          @click="selectTag(tag)"
        >
          {{ tag }}
        </el-tag>
        <a-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </a-input>
        <a-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标记</a-button>
        <div style="margin-bottom: 10px">已选标记</div>
        <div>
          <el-tag
            :key="tag"
            v-for="tag in selectTags"
            closable
            :disable-transitions="false"
            @close="handleSelectClose(tag)"
            type="success"
          >
            {{ tag }}
          </el-tag>
        </div>
        <div slot="footer" class="dialog-footer">
          <a-button @click="inputDialogVisible = false">取 消</a-button>
          <a-button type="primary" @click="inputDialogConfirm" v-loading="uploading">确 定</a-button>
        </div>
      </el-dialog>
      <el-dialog
        title="数据抓取中..."
        width="240px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        :visible.sync="batchVisible"
        custom-class="batchClass"
      >
        <div style="text-align: center">
          <el-progress type="circle" :percentage="percentage"></el-progress>
        </div>
      </el-dialog>

      <waybillForm ref="waybillForm" :parentObj="{ ...this }" />
      <waybillFormSplit ref="waybillFormSplit" :parentObj="{ ...this }" />
    </div>

    <printCopy ref="printCopy" />
    <ayncList
      ref="ayncList"
      @success="
        () => {
          this.pagination.current = 1
          this.getDataList()
        }
      "
    />
    <el-dialog title="导入" :visible.sync="upVisible" width="30%">
      <!-- :file-list="fileList" -->
      <!-- :action="$rootUrl+'/BO/BillList/ImportExcel'" -->

      <el-upload
        class="upload-demo"
        ref="upload"
        :action="$yooUrl + '/BO/BillList/ImportExcel?id=' + row.Id || ''"
        :on-change="handleChange"
        :on-success="onsuccess"
        accept=".xls,.xlsx"
        :limit="1"
        :auto-upload="false"
        :on-exceed="onexceed"
      >
        <el-button size="small" type="primary" icon="el-icon-upload2">选取文件</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="upVisible = false">取 消</el-button>
        <el-button type="primary" @click="rowUp" :loading="uploading">确 定</el-button>
      </span>
    </el-dialog>
  </a-card>
</template>

<script>
import radioGroup from '@/components/components/CompanyRadioGroup.vue'
import searchTip from '@/components/components/SearchTip.vue'
import moment from 'moment'
import _ from 'lodash'
import print from './print.vue'
import printCopy from './printCopy.vue'
import waybillForm from './waybillForm.vue'
import waybillFormSplit from './waybillFormSplit.vue'
import SendSMS from '../SendSMS/SendSMS.vue'
import ayncList from './ayncList.vue'

const options = [
  {
    value: '',
    label: '全部'
  },
  {
    value: '0',
    label: '待签收'
  },
  {
    value: '1',
    label: '已签收'
  },
  {
    value: '2',
    label: '拒签收'
  },
  {
    value: '3',
    label: '差异'
  },
  {
    value: '4',
    label: '作废'
  },
  {
    value: '-1',
    label: '待制单'
  }
]
const downloadFile = (url, downloadName = '') => {
  // console.log(url);
  const link = document.createElement('a')
  fetch(url)
    .then((res) => res.blob())
    .then((blob) => {
      link.href = URL.createObjectURL(blob)
      // console.log(link.href)
      link.download = downloadName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
}
export default {
  name: 'Home',
  components: { searchTip, radioGroup, waybillForm, SendSMS, print, printCopy, ayncList, waybillFormSplit },
  data () {
    return {
      qryDate: true,
      options,

      fileList: [],
      uploading: false,
      row: {},
      upVisible: false,
      redoLoading: false,
      tabsKey: '1',
      printData: {},
      printDataTo: {},
      activeName: '0',
      pagination: {
        current: 1,
        pageSize: 25,
        total: 0,
        pageSizeOptions: [25, 50, 100]
      },

      sorter: {
        field: 'CreateTime',
        order: 'desc'
      },
      tableData: [],
      queryParam: { SupplieId: '全部', Status: '', Condition: 'hzq', IsClose: 1 },
      keyword: '',
      loading: false,
      dialogVisible: false,
      templateId: '',
      selectTime: 0,
      templateList: [],
      time: [],
      timeDisabled: true,
      PriceTotal: 0,
      tabList: [
        { label: '全部', name: 'first' },
        { label: '待签收', name: '0' },
        { label: '已签收', name: '1' },
        { label: '差异', name: '3' },
        { label: '拒收', name: '2' },
        { label: '作废', name: '4' }
      ],
      ip: '',
      inputDialogVisible: false,
      inputVisible: '',
      inputValue: '',
      dynamicTags: [],
      selectTags: [],
      rowId: '',
      batchVisible: false,
      percentage: 0,
      TotalQuantity: 0,
      jumpId: null,
      modelContent: {},
      searchTipResultList: []
    }
  },
  mounted () {
    // this.getTemplateList()
    this.ip = sessionStorage.getItem('ip')
    this.time = [
      this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
      this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
    ]
  },
  computed: {
    height () {
      return document.documentElement.clientHeight * 0.75
    }
  },
  methods: {
    changeTime (e) {
      this.timeDisabled = true
      this.selectTime = e
      this.time = []
      switch (e) {
        case 0:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 1:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 2:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 3:
          this.timeDisabled = false
          break
      }
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },
    updateRunStatus (checked, event) {
      // console.log(checked)
      this.getDataList()
    },
    onsuccess (response, file, fileList) {
      if (response.Success) {
        this.uploading = false
        console.log(response, file, fileList)

        this.$message.success('导入成功')
        this.upVisible = false
      } else {
        this.$message.error(response.Msg)
        this.fileList = []
        this.uploading = false
      }
    },
    handleChange (file, fileList) {
      console.log(file, fileList)
      this.row.fileList = fileList
    },
    async rowUp () {
      console.log(this.row)
      console.log(this.fileList)
      if (!this.row.fileList.length) {
        return this.$message.warning('请选择文件后确定上传')
      }
      this.uploading = true
      await this.$refs.upload.submit()
    },
    onexceed (files, fileLis) {
      this.$message.warning('请删除文件后再选择')
    },
    uploadFile (params) {
      this.row.file = params.file
    },
    beforeupload (file) {
      console.log(file)
      return false
    },
    changeType (record, type) {
      this.loading = true
      this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/InvoiceOnOff?id=' + record.Id + '&type=' + type)
        .then((res) => {
          this.$message.success('操作成功!')
          this.getDataList()
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    upInfo (row) {
      this.row = row
      this.fileList = []
      this.upVisible = true
      this.row.fileList = []
      this.$nextTick(() => {
        this.$refs.upload.clearFiles()
      })
    },
    downloadFileInfo (data, name) {
      const blob = new Blob([data])
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      // console.log(link.href)
      link.download = name + '.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(link.href)
    },
    download (row) {
      this.$httpp
        .post(
          '/BO/BillList/ExportExcel',
          {
            id: row.Id
          },
          { responseType: 'blob' }
        )
        .then((res) => {
          console.log(res)
          // window.open(res)
          this.downloadFileInfo(res, row.BillId)
        })
      console.log(row.Id)
    },
    async aync () {
      // this.redoLoading = true
      // this.loading = true
      // await this.$http.post(`/InvoiceManagement/ST_RDRecord/AutomaticRecord`).then(res => {
      //   if (!res.Success) {
      //     this.redoLoading = false
      //     this.loading = false
      //     this.$message.error(res.Msg)
      //   }
      // })
      // if (!this.redoLoading) return
      // await this.$http.post(`/InvoiceManagement/ST_RDRecord/AutomaticRecordetail`).then(res => {
      //   if (!res.Success) {
      //     this.redoLoading = false
      //     this.loading = false
      //     this.$message.error(res.Msg)
      //   }
      // })
      this.redoLoading = false
      this.loading = false
      this.$refs.ayncList.open()
      // if (!this.redoLoading) return
      // await this.$http.post(`/InvoiceManagement/ST_RDRecord_b/ces`).then(async (res) => {
      //   if (res.Success) {
      //     await this.getDataList()
      //     this.$message.success(res.Data)
      //     this.redoLoading = false
      //   } else {
      //     this.$message.error('同步失败')
      //   }
      // })
    },
    getprintData (id) {
      this.$http.post(`/InvoiceManagement/Inv_Invoicing/GetAccountsales?Billid=${id}`).then((res) => {
        if (res.Success) {
          this.printData = res.Data || {}
        }
      })
    },
    getprintDataTwo (id) {
      this.$http.post(`/InvoiceManagement/Inv_Invoicing/GetAccompanyingGoods?Billid=${id}`).then((res) => {
        if (res.Success) {
          this.printDataTo = res.Data || {}
        }
      })
    },
    async dialogBatch (pageIndex) {
      if (pageIndex == 1) {
        if (
          !this.queryParam.SupplieId ||
          this.queryParam.SupplieId.split(',').length > 1 ||
          this.queryParam.SupplieId === '全部'
        ) {
          return this.$message.warning('请选择公司后新增')
        }
        this.batchVisible = true
        this.percentage = 0
      }
      await this.$httpp.post(`/BO/BillList/GetOrderList?pageIndex=${pageIndex}&pageRows=25`).then(async (res) => {
        if (res.Success) {
          const result = JSON.parse(res.Data)
          const newArr = result.data.list.map((item) => {
            return {
              Billid: item.order_no,
              Customer: item.user_name,
              CustomerId: item.user_code,
              Address: item.address_detail,
              CustomerPhone: item.receive_tel,
              create_time: item.delivery_date,
              Content: JSON.stringify({
                Subs: item.commodity_list.map((im) => {
                  return {
                    Name: im.commodity_name,
                    cInvCode: im.commodity_code,
                    Quantity: im.convert_amount,
                    GroupName: im.unit_sell,
                    iInvRCost: im.price,
                    cInvStd: im.summary,
                    SumiInvRCost: (im.convert_amount * im.price).toFixed(2)
                  }
                })
              })
            }
          })
          await this.saveDialogBatch(newArr)
          this.percentage = Math.floor((pageIndex / result.data.pageParams.total_page) * 100)
          if (pageIndex >= result.data.pageParams.total_page) {
            this.batchVisible = false
            return
          }
          await this.dialogBatch(pageIndex + 1)
        }
      })
    },
    async saveDialogBatch (arr) {
      await this.$httpp
        .post('/BO/BillList/SaveBillLists', {
          CompanyId: this.queryParam.SupplieId,
          billLists: arr
        })
        .then((res) => {
          console.log(res)
          this.getDataList()
        })
    },
    // 标记
    handelOpen (row) {
      this.rowId = row.Id
      if (row.Tag) this.selectTags = row.Tag.split(',')
      else this.selectTags = []
      let arr = localStorage.getItem('tagList')
      if (!arr) arr = []
      else arr = JSON.parse(arr)
      this.dynamicTags = arr
      this.inputDialogVisible = true
    },
    // 标记保存
    inputDialogConfirm () {
      if (this.inputVisible) {
        const inputValue = this.inputValue
        console.log(this.dynamicTags.findIndex((item) => item == this.inputValue))
        if (inputValue && this.dynamicTags.findIndex((item) => item == this.inputValue) == -1) {
          this.dynamicTags.push(inputValue)
        }
        this.inputValue = ''
      }
      localStorage.setItem('tagList', JSON.stringify(this.dynamicTags))
      if (this.selectTags.length <= 0) {
        return this.$message.error('请至少选择一项')
      }
      this.$httpp
        .post('/BO/BillList/UpdateTag', {
          Id: this.rowId,
          Tag: this.selectTags.join(',')
        })
        .then((res) => {
          if (res.Success) {
            this.$message.success('操作成功')
            this.getDataList()
            this.inputDialogVisible = false
          } else this.$message.error(res.Msg)
        })
    },
    selectTag (tag) {
      console.log(tag)
      const idx = this.selectTags.findIndex((item) => item == tag)
      if (idx == -1) this.selectTags.push(tag)
      else this.selectTags.splice(idx, 1)
    },
    // 标签删除
    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    // 已选标签删除
    handleSelectClose (tag) {
      this.selectTags.splice(this.selectTags.indexOf(tag), 1)
    },
    // 增加标签
    showInput () {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm () {
      const inputValue = this.inputValue
      if (inputValue && this.dynamicTags.findIndex((item) => item == this.inputValue) == -1) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 编辑
    openwaybillForm (row) {
      this.$httpp.post('/BO/BillList/GetTheBillData', { id: row.Id }).then((res) => {
        if (res.Success) {
          console.log(res)
          this.$refs.waybillForm.openForm(res.Data, '1', row.Company, '')
        } else {
          this.$message.error(res.Msg)
        }
      })
    },
    // 拆单
    openwaybillFormSplit (row) {
      this.$httpp.post('/BO/BillList/GetTheBillData', { id: row.Id }).then((res) => {
        if (res.Success) {
          console.log(res)
          this.$refs.waybillFormSplit.openForm(res.Data, '1', row.Company, '', row)
        } else {
          this.$message.error(res.Msg)
        }
      })
    },
    // 同意差异
    differentConfrim (row) {
      this.$httpp.post('/BO/BillList/ConfigSubmit?Id=' + row.Id + '&IP=' + this.ip).then((res) => {
        if (res.Success) {
          this.getDataList()
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.Msg)
        }
      })
    },
    // 重启
    resetStart (row, type) {
      let url = ''
      if (type == 'confirm') url = '/BO/BillList/WebForm'
      else url = '/BO/BillList/Processing'
      this.$httpp.post(url + '?Id=' + row.Id).then((res) => {
        if (res.Success) {
          this.getDataList()
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.Msg)
        }
      })
    },
    // 重置
    resetTemplate (row) {
      this.$confirm('此操作将改变当前货单模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$httpp.post('/BO/BillList/ResetFormTemplate?Id=' + row.Id + '&CommpayId=' + row.Company).then((res) => {
          if (res.Success) {
            this.$message.success('操作成功')
          } else {
            this.$message.error(res.Msg)
          }
        })
      })
    },
    radioComplete (e) {
      if (e) {
        this.queryParam.SupplieId = e
        this.getDataList()
      }
    },
    // 打开单据页面
    openNewPage (row) {
      console.log('打开单据页面', row)
      this.$refs.printCopy.openInit(row.Id)

      // const token = JSON.parse(localStorage.getItem('ReceiptSign_token')).token
      // this.printData = {}
      // this.printDataTo = {}
      // this.getprintData(row.BillId)
      // this.getprintDataTwo(row.BillId)
      // this.tabsKey = '1'
      // this.jumpId = row.Id + '&' + token
      // localStorage.setItem('sendRowData', JSON.stringify(row))
      // const isClient = sessionStorage.getItem('client')
      // let url = `${location.href.split('ReceiptSign')[0]}ReceiptSign/SendSMS/SendSMS?prop=${row.Id}`
      // if (isClient) {
      //   console.log(url)
      //   url = `${location.href.split('#')[0]}#/SendSMSCopy?prop=${row.Id}`
      // }
      // window.open(url, "_blank");
    },
    // 新增电子回执
    async dialogConfirm () {
      // if (!this.templateId) return this.$message.error("请选择模板");
      if (
        !this.queryParam.SupplieId ||
        this.queryParam.SupplieId.split(',').length > 1 ||
        this.queryParam.SupplieId === '全部'
      ) {
        return this.$message.warning('请选择公司后新增')
      }
      const result = await this.$httpp.post(
        '/Base_Manage/Base_Company/DataIntegrity?CommpayId=' + this.queryParam.SupplieId
      )
      if (!result.Success) return this.$message.error(result.Msg)
      this.loading = true
      this.$httpp.post(`/Base/Base_Template/GetCompanyTemp?CompayId=${this.queryParam.SupplieId}`).then((res) => {
        if (res.Success) {
          this.$refs.waybillForm.openForm(res.Data.Content, '', this.queryParam.SupplieId, res.Data.TemName)
          this.dialogVisible = false
        } else {
          this.$message.error(res.Msg)
        }
        this.loading = false
      })
      // this.$httpp
      //   .post('/Base/Base_Template/GetTemplateDefault', {})
      //   .then((res) => {
      //     if (res.Success) {
      //       this.$refs.waybillForm.openForm(res.Data.Content)
      //       this.dialogVisible = false
      //     } else {
      //       this.$message.error(res.Msg)
      //     }
      //     this.loading = false
      //   })
      // this.$refs.waybillForm.openForm(
      //   // this.templateList[this.templateId].Content
      //   this.templateList[this.templateList.length - 1].Content
      // )
      // this.dialogVisible = false;
    },
    // 公司切换
    radioChange (e) {
      if (e == 'more') return
      this.queryParam.SupplieId = e
      this.getDataList()
    },
    // 页签切换
    handleClick (tab, event) {
      this.pagination = {
        current: 1,
        pageSize: 25,
        total: 0,
        pageSizeOptions: [25, 50, 100]
      }
      this.queryParam.Status = this.activeName + ''
      if (this.activeName == 'first') this.queryParam.Status = ''
      this.getDataList()
    },
    // 下载
    handleDownload (scope) {
      this.$httpp.post('/BO/BillList/GetPDF?id=' + scope.Id).then((res) => {
        if (res.Success) {
          downloadFile(res.Data, scope.BillId)
        } else {
          this.$message.error(res.Msg)
        }
      })
    },
    // 作废
    handleInvalidate (scope) {
      this.$confirm('确认要作废本条单据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post('/InvoiceManagement/ST_RDRecord/BillToVoid?id=' + scope.Id + '&code=' + scope.BillId)
          .then((res) => {
            // this.$httpp.post('/BO/BillList/ToVoid?Billd=' + scope.Id + '&IP=' + this.ip).then((res) => {
            if (res.Success) {
              this.$message.success('操作成功')
              this.getDataList()
            } else {
              this.$message.error(res.Msg)
            }
          })
      })
    },
    // 模板列表
    getTemplateList () {
      this.$httpp.post('/Base/Base_Template/GetDataList', {}).then((res) => {
        if (res.Success) {
          this.templateList = res.Data
        }
      })
    },
    currentChange (page) {
      this.pagination.current = page
      this.getDataList()
    },
    handleSizeChange (lint) {
      this.pagination.pageSize = lint
      this.getDataList()
    },
    async getDataList () {
      this.searchTipResultList = [] // 清空搜索提示列表

      this.loading = true
      this.queryParam.DateType = this.qryDate ? 1 : 0
      await this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetBillList', {
          // await this.$httpp
          //   .post('/BO/BillList/GetBillList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: {
            ...this.queryParam,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : ''
          }
        })
        .then((resJson) => {
          this.loading = false
          if (resJson.Success) {
            this.tableData = resJson.Data
            this.PriceTotal = resJson.TotalMoney
            this.TotalQuantity = resJson.TotalQuantity
            if (this.tableData) {
              const pagination = { ...this.pagination }
              pagination.total = resJson.Total
              this.pagination = pagination
            }
          }
        })
      // this.$http.post('/InvoiceManagement/ST_RDRecord/GetCustomerRecordsTotal',{
      //   PageIndex: this.pagination.current,
      //   PageRows: this.pagination.pageSize,
      //   SortField: this.sorter.field || 'Id',
      //   SortType: this.sorter.order,
      //   Search: this.queryParam
      // }).then(res=>{

      // })
    },
    async toGetSearchTipList (e) {
      this.searchTipResultList = []
      this.queryParam.keyword = e
      if (!this.queryParam.keyword) {
        return
      }
      this.queryParam.DateType = this.qryDate ? 1 : 0
      await this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetBillList', {
          // await this.$httpp
          //   .post('/BO/BillList/GetBillList', {
          PageIndex: 1,
          PageRows: 10,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: {
            ...this.queryParam,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : ''
          }
        })
        .then((resJson) => {
          if (resJson.Success && this.queryParam.keyword) {
            this.searchTipResultList = resJson.Data.map((e) => e.Customer).slice(0, 10)
          } else {
            this.searchTipResultList = []
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    selectSearchTipFun (text) {
      this.queryParam.keyword = text
      this.searchTipResultList = []
      this.getDataList()
    },

    keywordBlurFun () {
      this.searchTipResultList = []
    }
  }
}
</script>

<style lang="less" scoped>
.ant-switch-checked:nth-child(1) {
  background-color: #1890ff;
}

.ant-switch {
  background-color: #1890ff;
  height: 34px;
  width: 100px;
  margin-top: -3px;
  margin-left: 4px;
}

&.ant-switch::after {
  width: 26px;
  height: 26px;
  top: 3px;
}

// /deep/.batchClass{
//   // background-color: #ffffffe9;
// }
.searchNav .a-button {
  background: #1890ff;
  border-color: #1890ff;
  color: #fff;
}

/deep/.el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
  box-shadow: -1px 0 0 0 #1890ff;
}

/deep/.el-radio-button__inner:hover {
  color: #1890ff;
}

.el-ra .el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.button-new-tag {
  margin-bottom: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-bottom: 10px;
  // vertical-align: bottom;
}

.tableEltag {
  margin: 0;
}

/deep/ .el-tabs__nav {
  width: 100%;
  background: #fff;
}

/deep/ .el-tab-pane {
  width: 100%;
  background: #fff;
}

/deep/ .el-tabs__item {
  width: 16.6%;
  text-align: center;
  font-weight: bold;
  padding: 0;
}

/deep/ .el-tabs__item:hover {
  background: #ecf5ff;
}

/deep/ .ant-drawer-body {
  padding: 0 20px;
}
/deep/ .ant-card-body {
  padding-bottom: 5px;
}
</style>
